package singleton;

//懒汉式单例模式写法
public class LazyType {

    public static boolean flag = false;
//    private LazyType(){
//        System.out.println(Thread.currentThread().getName()+"创建了线程");
//    }
        private LazyType(){
            synchronized (LazyType.class){
                if(flag == false){
                    flag = true;
                }else {
                    throw new RuntimeException("请不要刻意使用反射去破坏游戏规则！");
                }
            }
            System.out.println(Thread.currentThread().getName()+"创建了线程");
        }

    private volatile static LazyType lazyType;

    public static LazyType getLazyType(){

        //普通懒汉式存在线程不安全问题
//        if (lazyType == null){
//            lazyType = new LazyType();
//        }
//        System.out.println(Thread.currentThread().getName()+"输出了对象");
//        return lazyType;

        //双重检验锁可以确保线程安全----->DCL懒汉式
        //可能出现指令重排，需在对象声明时加volatile关键字
        if(lazyType == null){
            synchronized (LazyType.class){
                if (lazyType == null){
                    lazyType = new LazyType();
                }
            }
        }
        System.out.println(Thread.currentThread().getName()+"输出了对象"+lazyType);
        return lazyType;
    }
}
